$(document).ready(function () {

  layui.use(function () {

    var layer = layui.layer;


    // 右侧树
    tree = layui.tree;

    // 表格
    form = layui.form;
    form.on('select(needCharge)', function (data) {//监听是否充电查询条件下拉
      $('div[lay-filter="search"]').click();
    });

    form.on('submit(search)', function (data) {//监听查询提交
      params = data.field;
      params.pageSize = 10;
      queryTable()
      return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
    });


    form.on('submit(edit)', function (data) {//监听新增修改提交

      let msgType = "";
      if (curId) {
        msgType = "编辑"
        data.field.id = curId
      } else {
        msgType = "新增"
      }

      new AjaxChain()
        .setUrl('/role/save')
        .setMethod('post')
        .setData(JSON.stringify(data.field))
        .then(data => {
          layer.close(drawer);
          layer.msg(msgType + '成功', { icon: 1, time: 2000 });
          queryTable()
        })
        .catch(err => {
          console.error('请求异常:', err);
        })
        .send();


      return false;
    });


    initSubMenu();
    queryTable();
    loadTree()


  });


})
var params = {};//查询条件参数
var form, unit, tree;
var drawer;//抽屉实例
var curId = null;//当前选中物资ID
var allIds = [];//获取选中菜单id
var curRoleId = null;//当前选中的菜单id


queryTable = () => {
  let toolWidth = window.innerWidth / 1920 * 240
  layui.use('table', function () {
    var table = layui.table;

    //展示已知数据
    table.render({
      elem: '#table'
      , text: {
        none: '暂无数据'
      }
      , method: 'get'
      , url: ajaxPrefix() + "/role/list"
      , headers: {
        SessionId: JSON.parse(localStorage.getItem('sessionId'))
      }
      , where: params
      , parseData: function (res) { //res 即为原始返回的数据
        return {
          "code": res.status == 200 ? 0 : 1, //解析接口状态
          "msg": res.message, //解析提示文本
          "count": res.result.total, //解析数据长度
          "data": res.result.data //解析数据列表
        };
      }
      , request: {
        pageName: 'pageNum' //页码的参数名称，默认：page
        ,
        limitName: 'pageSize' //每页数据量的参数名，默认：limit
      }
      , cols: [[ //标题栏
        { field: 'name', title: '角色名称', align: "center" }
        , { field: 'description', title: '描述', align: "center" }
        , {
          title: '操作',
          align: 'center',
          width: toolWidth,
          templet: function (d) {
            let res = JSON.stringify(d);
            return `<div class="table-tool">
                              <div onclick='tableHandle(1,${res},event)' class="table-edit layui-btn">
                                <img src="../static/img/edit.png">编辑
                              </div>
                              <div onclick='tableHandle(2,${res},event)' class="table-del layui-btn">
                                <img src="../static/img/del.png">删除
                              </div>
                            </div>`;
          },
        },
      ]]
      , height: 'full'
      // ,skin: 'line' //表格风格
      , even: true
      , page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
        layout: ['count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
        //,curr: 5 //设定初始在第 5 页
        , groups: 3 //只显示 1 个连续页码
        , first: false //不显示首页
        , last: false //不显示尾页

      }
      , done: function (res, curr, count) {

        $('.layui-table-cell').height($('.contain-table-list').height() / 20);
      },

    });
    table.on('row(table)', function (obj) {

      obj.setRowChecked({ type: 'radio' });

      var data = obj.data; // 获取当前行数据

      curRoleId = data.id


      new AjaxChain()
        .setUrl('/menu/role')
        .setData({
          "roleId": curRoleId,
        })
        .then(data => {
          tree.reload('tree')
          var ids = data.filter(item => item.pId != '' && item.pId != null)
            .map(function (item) {
              return item.id;
            })

          tree.setChecked('tree', ids);

        })
        .catch(err => {
          console.error('请求异常:', err);
        })
        .send();


    });

  });
}


// 列表功能按钮操作
tableHandle = (type, res, e) => {
  if (e) e.stopPropagation()


  switch (type) {
    case 1://编辑
      curId = res.id
      openDrawer(2, res)
      break;
    case 2://删除

      layer.confirm('确定删除该记录吗？', { icon: 3 }, function () {

        new AjaxChain()
          .setUrl('/role/delete')
          .setData({ id: res.id })
          .then(data => {
            layer.msg('删除成功', { icon: 1, time: 1500 });
            queryTable();
          })
          .catch(err => {
            console.error('请求异常:', err);
          })
          .send();
      });
      break;

    case 3://新增 
      curId = null;
      openDrawer(1)
      break;
    case 4://刷新
      new AjaxChain()
        .setUrl('/menu/role')
        .then(data => {

          const menuData = buildTree(data);
          localStorage.setItem('menu', JSON.stringify(menuData));
          layer.msg('菜单权限已更新')
        })
        .catch(err => {
          console.error('请求异常:', err);
        })
        .send();
      break;


    default:
      break;
  }
}


//新增修改弹窗
openDrawer = (type, res) => {
  drawer = layer.open({
    title: (type == 1 ? "新增" : "编辑") + '角色',
    type: 1,
    offset: 'r',
    anim: 'slideLeft', // 从右往左
    area: ['30%', '100%'],
    shade: 0.3,
    shadeClose: false,
    id: 'edit-offset',
    success: function (layero, index, that) {
      if (res) {
        form.val('editForm', res);

      } else {
        form.render(null, 'editForm');
      }
    },
    content: `<form class="layui-form layui-form-pane" id="add-form"  lay-filter="editForm"  action="">
                  <div class="form-item">
                      <label class="layui-form-label">角色名称</label>
                      <div class="layui-input-block">
                          <input type="text" name="name" lay-affix="clear" placeholder="请输入" lay-verify="required"
                              class="layui-input">
                      </div>
                  </div>
                  <div class="form-item">
                      <label class="layui-form-label">角色描述</label>
                      <div class="layui-input-block">
                          <input type="text" name="description" lay-affix="clear" placeholder="请输入"
                              class="layui-input">
                      </div>
                  </div>
                  <div class="form-item pane-tool" >
                      <button type="reset" class="layui-btn layui-btn-primary btn-reset">重置</button>
                      <button class="layui-btn" lay-submit lay-filter="edit">确认</button>
                  </div>
              </form>`
  });

}


// 加载菜单树
loadTree = () => {


  new AjaxChain()
    .setUrl('/menu/list/all')
    .then(data => {


      // 将平铺数据转换为嵌套数据
      function buildTree(flatData, parentId) {
        var treeData = [];
        flatData.forEach(function (item) {
          if (item.pId === parentId) {
            var children = buildTree(flatData, item.id);
            if (children.length) {
              item.children = children;
            }
            treeData.push(item);
          }
        });
        return treeData;
      }


      tree.render({
        elem: '#tree',
        id: "tree",
        data: buildTree(data, ''),
        customName: {
          id: 'id',
          title: 'name',
        },
        showCheckbox: true,
        showLine: false

      });

    })
    .catch(err => {
      console.error('请求异常:', err);
    })
    .send();

}



// 保存角色菜单权限

$('#save-rolemenu-button').click(function () {

  if (curRoleId) {

    var checkData = tree.getChecked('tree');
    allIds = [];
    // 对树形结构中的每个顶级节点调用递归函数
    checkData.forEach(function (node) {
      extractIds(node);
    });


    new AjaxChain()
      .setUrl('/menu/role/save')
      .setMethod('POST')
      .setData(JSON.stringify({
        "roleId": curRoleId,
        "menuRoleList": allIds
      }))
      .then(data => {
        layer.msg('保存成功', { icon: 1, time: 1500 });
      })
      .catch(err => {
        console.error('请求异常:', err);
      })
      .send();


  } else {
    layer.msg('请先单击左侧列表选择分配角色')
  }

})


// 递归函数来提取所有节点的 id
function extractIds(node) {

  allIds.push(node.id);

  // 如果节点有子节点，则递归调用此函数
  if (node.children && node.children.length > 0) {
    node.children.forEach(function (child) {
      extractIds(child);
    });
  }
}